<template>
  <div ref="chartRef" class="h-full w-full"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from "vue";
import * as echarts from "echarts";
import "echarts-gl";

interface Props {
  option: echarts.EChartsOption;
  theme?: string;
}

const props = withDefaults(defineProps<Props>(), {
  theme: "dark",
});

const chartRef = ref<HTMLDivElement>();
let chartInstance: echarts.ECharts | null = null;

// 初始化图表
const initChart = () => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value, props.theme);
    chartInstance.setOption(props.option);
  }
};

// 销毁图表
const destroyChart = () => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
};

// 重新渲染图表
const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

// 监听配置变化
watch(
  () => props.option,
  (newOption) => {
    if (chartInstance) {
      chartInstance.setOption(newOption, true);
    }
  },
  { deep: true }
);

// 监听窗口大小变化
const handleResize = () => {
  resizeChart();
};

onMounted(async () => {
  await nextTick();
  initChart();
  window.addEventListener("resize", handleResize);
});

onUnmounted(() => {
  destroyChart();
  window.removeEventListener("resize", handleResize);
});

// 暴露方法给父组件
defineExpose({
  getChartInstance: () => chartInstance,
  resize: resizeChart,
});
</script>
